<?php
class Lawyer extends Eloquent {

	const POSITION_JUNIOR = 'junior_lawyer';
	const POSITION_SENIOR = 'senior_lawyer';
	const POSITION_PARTNER = 'partner';

	protected $table = 'lawyer';

	protected $primaryKey='user_id';
	/**
	 * 软删除
	 * @var boolean
	 */
	protected $softDelete = true;	
	public function user()
	{
		return $this->belongsTo('User');
	}

	public static function getLawyers(
		$cat_id,
		$province_id,
		$city_id, 
		$district_id,
		$search, 
		$practice_period,
		$offset, 
		$limit, 
		$created_at = NULL, 
		$order_by = 'user.created_at', 
		$direction = 'DESC',
		$is_recommended)
	{
		return User::whereHas('lawyer', function ($query) use($cat_id, $practice_period) {
			if ($cat_id) {
				$query->where("work_scope", "like", "%" . $cat_id . "%");
			}
			if ($practice_period) {
				$query->where("practice_period", $practice_period);
			}
		})->leftJoin("lawyer", "user.id", "=", "lawyer.user_id")
			->where("user.status", User::STATUS_VERIFIED_LAWYER)
			->OfCityId($city_id)
			->OfProvinceId($province_id)
			->OfDistrictId($district_id)
			->OfSearch($search)
			->OfCreatedAt($created_at)
			->OfIsRecommended($is_recommended)
			->take($limit)
			->skip($offset)
			->orderBy($order_by, $direction)
			->get();
	}

	public static function getLawyersByCategory($cat_id)
	{
		return User::whereHas('lawyer', function ($query) use($cat_id) {
			$query->where("work_scope", "like", "%" . $cat_id . "%");
		})->where("status", User::STATUS_VERIFIED_LAWYER)->get();
	}

	public static function getLawyerList($q, $rows_per_page, $offset, $exclude, $cond)
	{
		$query = User::join('lawyer', 'lawyer.user_id', '=', 'user.id')
			->select(
				'user.id as user_id',
				'user.avatar',
				'user.realname'
			)
			->whereNotIn('user.id', $exclude)
			->take($rows_per_page)
			->skip($offset);

		if ($q) {
			$query = $query->where('user.realname', 'like', "%$q%");
		}

		if (isset($cond['city'])) {
			$query = $query->where('user.city', '=', $cond['city']);
		}
		if (isset($cond['cat_id'])) {
			$scope = $cond['cat_id'];
			$query = $query->where('lawyer.work_scope', 'like', "%$scope%");
		}
		if (isset($cond['experience'])) {
			$query = $query->where('lawyer.practice_period', '=', $cond['experience']);
		}

		return $query->get();
	}

	public static function getUserByScope($scope_id)
	{
		return self::select(['user_id'])->where('work_scope', 'like', "%{$scope_id}%")->get();
    }

}